package com.ezjie.ielts.module_read;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ezjie.ielts.R;
import com.ezjie.ielts.constant.Constants;
import com.ezjie.ielts.core.base.BaseFragmentActivity;
import com.ezjie.ielts.model.FullTextInfo;
import com.ezjie.ielts.model.GroupInfo;
import com.ezjie.ielts.model.SubmitGroupInfo;
import com.ezjie.ielts.module_read.originpager.ReadOriginPagerFragment;
import com.ezjie.ielts.util.AnimUtils;
import com.ezjie.ielts.util.DensityUtil;
import com.ezjie.ielts.util.StringUtil;
import com.ezjie.ielts.util.UmengPages;
import com.ezjie.ielts.view.FlowLayout;
import com.ezjie.ielts.widget.MyScrollView;
import com.ezjie.ielts.widget.MyScrollView.OnScrollListener;
import com.ezjie.ielts.widget.TitleTextView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.analytics.MobclickAgent;

@ContentView(R.layout.activity_answer_anlysis)
public class ReadAnswerAnlysisActivity extends BaseFragmentActivity implements OnScrollListener {

	@ViewInject(R.id.rl_answer_anlysis_root)
	private RelativeLayout rl_answer_anlysis_root;
	@ViewInject(R.id.iv_topbar_back)
	private ImageView iv_topbar_back;
	@ViewInject(R.id.tv_topbar_title)
	private TitleTextView tv_topbar_title;
	@ViewInject(R.id.tv_originpage)
	private TextView tv_originpage;
	@ViewInject(R.id.fragment_originpager)
	private FrameLayout fragment_originpager;
	@ViewInject(R.id.tv_read_exercises_title)
	private TextView tv_read_exercises_title;
	@ViewInject(R.id.tv_read_exercises_title_detail)
	private TextView tv_read_exercises_title_detail;
	@ViewInject(R.id.tv_read_exercises_content)
	private TextView tv_read_exercises_content;
	@ViewInject(R.id.tv_read_exercises_pic)
	private TextView tv_read_exercises_pic;
	@ViewInject(R.id.iv_read_exercises_pictrue)
	private ImageView iv_read_exercises_pictrue;
	@ViewInject(R.id.iv_read_exercises_pictrue2)
	private ImageView iv_read_exercises_pictrue2;
	@ViewInject(R.id.ll_read_exercises_question)
	private LinearLayout ll_read_exercises_question;
	@ViewInject(R.id.ll_read_exercises_pictrue)
	private RelativeLayout ll_read_exercises_pictrue;
	@ViewInject(R.id.ll_read_exercises_pictrue2)
	private RelativeLayout ll_read_exercises_pictrue2;
	@ViewInject(R.id.ll_read_click_question_point)
	private LinearLayout ll_read_click_question_point;
	@ViewInject(R.id.tv_fill_smalltitle)
	private TextView tv_fill_smalltitle;
	@ViewInject(R.id.ll_read_top)
	private LinearLayout ll_read_top;
	@ViewInject(R.id.scroll_fill_layout)
	private MyScrollView scroll_fill_layout;

	private long duration = 250;
	private int myLayoutTop;

	private GroupInfo data;
	private FullTextInfo origindata;
	private SubmitGroupInfo submitdata;

	private ReadOriginPagerFragment pagerFragment;
	private List<ImageView> mPointImageView = new ArrayList<ImageView>(); // 切题时右侧提示浮点
	private static DisplayImageOptions options;
	private GestureDetector mGestureDetector;
	private List<View> mAnswerView = new ArrayList<View>(); // 当前查看题组的答案解析view集合

	private int mCurrentQuestion;

	private boolean isScrollBottom;
	private boolean isScrollTop;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ViewUtils.inject(this);
		options = new DisplayImageOptions.Builder().showStubImage(R.drawable.default_img) // 设置图片在下载期间显示的图片
				.showImageForEmptyUri(R.drawable.default_img) // 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.default_img) // 设置图片加载/解码过程中错误时候显示的图片
				.cacheInMemory() // 是否緩存都內存中
				.cacheOnDisc() // 是否緩存到sd卡上
				.build();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
		ImageLoader.getInstance().init(config);

		init();
	}

	/**
	 * "1" => "单选", "2" => "多选题","3"=>
	 * '带选项图表题','4'=>'配对题','5'=>'标题对应题','6'=>'是非题','7'=>'摘要题','8'=>'简答题',
	 * '9'=>'完成句子题','10'=>'不带选项卡图表题','11'=>'表格题','12'=>'带图选择题',
	 * '13'=>'带选项摘要题',"14"=>'带选项的完成句子题 '
	 */
	private void init() {
		Bundle bundle = getIntent().getBundleExtra(Constants.READ_INSTANT_REPORT_BUNDLE);
		data = (GroupInfo) bundle.getSerializable(Constants.READ_INSTANT_REPORT_ANSWER);
		origindata = (FullTextInfo) bundle.getSerializable(Constants.READ_SETDATA_SINGLE_ORIGIN);
		submitdata = (SubmitGroupInfo) bundle.getSerializable(Constants.READ_INSTANT_REPORT_SUBMIT_ANSWER);
		mCurrentQuestion = bundle.getInt(Constants.READ_POSITION, 0);
		listenerSoftInput();
		tv_topbar_title.setText(R.string.read_answer_analysis_title);
		iv_topbar_back.setOnClickListener(this);
		tv_originpage.setOnClickListener(this);
		initOriginPager();

		scroll_fill_layout.setOnScrollListener(this);
		addAnswerAnalysisView();

		switch (Integer.parseInt(data.group_type)) {
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
		case 6:
		case 7:
		case 8:
		case 9:
		case 10:
		case 11:
		case 12:
		case 13:
		case 14:
			if (Integer.parseInt(data.group_type) == 11) {
				// tv_read_exercises_pic.setVisibility(View.VISIBLE);
			}
			tv_fill_smalltitle.setText(String.format(getResources().getString(R.string.read_task_name), data.book_name,
					data.task) + " " + data.group_name);
			tv_read_exercises_title.setText(String.format(getResources().getString(R.string.read_task_name),
					data.book_name, data.task));
			tv_read_exercises_title_detail.setText(data.group_name);
			tv_read_exercises_content.setText(data.content);

			iv_read_exercises_pictrue.setOnClickListener(this);
			iv_read_exercises_pictrue2.setOnClickListener(this);
			if (!TextUtils.isEmpty(data.img_1)) {
				ImageLoader.getInstance().displayImage(data.img_1, iv_read_exercises_pictrue, options);
			} else {
				ll_read_exercises_pictrue.setVisibility(View.GONE);
			}
			if (!TextUtils.isEmpty(data.img_2)) {
				ImageLoader.getInstance().displayImage(data.img_2, iv_read_exercises_pictrue2, options);
			} else {
				ll_read_exercises_pictrue2.setVisibility(View.GONE);
			}

			if (Constants.ReadClassifyGroupType.SUMMARY.equals(data.group_type)
					|| Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(data.group_type)) {
				ll_read_click_question_point.setVisibility(View.GONE);
				for (int i = 0; i < mAnswerView.size(); i++) {
					ll_read_exercises_question.addView(mAnswerView.get(i));
				}
			} else {
				mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
					@Override
					public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
						// if (Math.abs(e1.getRawX() - e2.getRawX()) > 250) {
						// // System.out.println("水平方向移动距离过大");
						// return true;
						// }
						// if (Math.abs(velocityY) < 200) {
						// // System.out.println("手指移动的太慢了");
						// return true;
						// }

						// 手势向下 down
						if (isScrollTop && ((e2.getRawY() - e1.getRawY()) > 200)) {
							if (mCurrentQuestion > 0) {
								AnimUtils.downAnim(ReadAnswerAnlysisActivity.this, scroll_fill_layout);
								scroll_fill_layout.scrollTo(0, 0);
								tv_fill_smalltitle.setVisibility(View.GONE);
								mCurrentQuestion = switchLookAnswer(mCurrentQuestion - 1);
							}

							// 在此处控制关闭
							return true;
						}
						// 手势向上 up
						if (isScrollBottom && ((e1.getRawY() - e2.getRawY()) > 200)) {
							if (data.questions_list.size() - 1 > mCurrentQuestion) {
								scroll_fill_layout.scrollTo(0, 0);
								tv_fill_smalltitle.setVisibility(View.GONE);
								AnimUtils.upAnim(ReadAnswerAnlysisActivity.this, scroll_fill_layout);
								mCurrentQuestion = switchLookAnswer(mCurrentQuestion + 1);
							}
							return true;
						}
						return super.onFling(e1, e2, velocityX, velocityY);
					}
				});
				initPointView();
				mCurrentQuestion = switchLookAnswer(mCurrentQuestion);
			}

			break;

		default:
			break;
		}
	}

	/**
	 * 查看答案解析 - 切换
	 * 
	 * @param number
	 * @return
	 */
	private int switchLookAnswer(int number) {

		ll_read_exercises_question.removeAllViews();
		ll_read_exercises_question.addView(mAnswerView.get(number));

		if (mPointImageView.size() > 1) {
			for (int i = 0; i < mPointImageView.size(); i++) {
				if (i == number) {
					mPointImageView.get(i).setImageResource(R.drawable.question_point_checked);
				} else {
					mPointImageView.get(i).setImageResource(R.drawable.question_point_normal);
				}
			}
		} else {
			ll_read_click_question_point.setVisibility(View.INVISIBLE);
		}

		return number;
	}

	/**
	 * 添加答案解析view集合
	 */
	@SuppressLint("NewApi")
	private void addAnswerAnalysisView() {
		for (int i = 0; i < data.questions_list.size(); i++) {
			String myAnswer = submitdata.questions.get(i).answer;
			View analysisview = null;
			if (Constants.ReadClassifyGroupType.SUMMARY.equals(data.group_type)
					|| Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(data.group_type)) {
				analysisview = LayoutInflater.from(this).inflate(R.layout.layout_summary_answer_anlysis, null);
			} else {
				analysisview = LayoutInflater.from(this).inflate(R.layout.layout_answer_analysis, null);
			}
			TextView youranswer = (TextView) analysisview.findViewById(R.id.tv_read_your_answer);
			TextView rightanswer = (TextView) analysisview.findViewById(R.id.tv_read_right_answer);
			TextView answeranalysis = (TextView) analysisview.findViewById(R.id.tv_read_answer_analysis);
			TextView tv_read_question = (TextView) analysisview.findViewById(R.id.tv_read_question);

			TextView analysistv = (TextView) analysisview.findViewById(R.id.tv_read_answer_analysis_title);
			if (!TextUtils.isEmpty(data.questions_list.get(i).describe)) {
				answeranalysis.setText(data.questions_list.get(i).describe);
			} else {
				analysistv.setVisibility(View.GONE);
				answeranalysis.setVisibility(View.GONE);
			}

			String questionstr = data.questions_list.get(i).question;
			questionstr = questionstr.replace(Constants.READ_EDIT_MERGE, " ");
			if (null != tv_read_question) {
				youranswer.setTextColor(getResources().getColor(R.color.ask_right));

				if (Constants.READ_EDIT_LINE.equals(questionstr)) {
					questionstr = "";
				}
				tv_read_question.setText(Html.fromHtml(data.questions_list.get(i).no
						+ ".  "
						+ questionstr.replace(Constants.READ_EDIT_LINE,
								getResources().getString(R.string.read_text_under_line))));
				if (Constants.ReadClassifyGroupType.TRUE_OR_FALSE.equals(data.group_type)) {
					rightanswer.setText(StringUtil.getAnswerStr(StringUtil
							.getRightAnswerListByTrueOrFlase(data.questions_list.get(i).answer)));
				} else {
					rightanswer.setText(StringUtil.getAnswerStr(StringUtil.getRightAnswerList(data.questions_list
							.get(i).answer)));
				}
				if (submitdata.questions.get(i).is_right.equals("false")) {
					if (Constants.ReadClassifyGroupType.MULTIPLE_CHOICE.equals(data.group_type)) {
						List<String> myAnswerlist = StringUtil.getAnswerList(myAnswer);
						SpannableStringBuilder builder = new SpannableStringBuilder();
						for (int j = 0; j < myAnswerlist.size(); j++) {
							builder.append(myAnswerlist.get(j) + "\r\n");
							if (!StringUtil.contains(StringUtil.getRightAnswerList(data.questions_list.get(i).answer),
									myAnswerlist.get(j))) {
								ForegroundColorSpan redSpan = new ForegroundColorSpan(getResources().getColor(R.color.ask_wrong));
								builder.setSpan(redSpan, builder.length() - (myAnswerlist.get(j).length() + 2),
										builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							}
						}
						youranswer.setText(builder);
					} else {
						youranswer.setTextColor(getResources().getColor(R.color.ask_wrong));
						youranswer.setText(myAnswer);
					}
				} else {
					youranswer.setText(myAnswer);
				}
			} else {
				FlowLayout summary_tv_read_question = (FlowLayout) analysisview
						.findViewById(R.id.tv_summary_read_question);
				MarginLayoutParams layoutParams = new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT,
						MarginLayoutParams.WRAP_CONTENT);
				layoutParams.setMargins(0, DensityUtil.dip2px(this, 3), DensityUtil.dip2px(this, 3),
						DensityUtil.dip2px(this, 3));
				rightanswer
						.setText(StringUtil.getAnswerStr(StringUtil.getRightAnswerList(data.questions_list.get(i).answer)));

				String regEx = "[.|!|?]";
				Pattern p = Pattern.compile(regEx);
				Matcher m = p.matcher(questionstr);
				String[] strss = p.split(questionstr);
				if (strss.length > 0) {
					int count = 0;
					while (count < strss.length) {
						if (m.find()) {
							strss[count] += m.group();
						}
						count++;
					}
				}
				for (String strsss : strss) {
					String[] str1s = strsss.split(" ");

					for (String str : str1s) {
						if (str.contains(Constants.READ_EDIT_LINE)) {

							final EditText edittext = (EditText) LayoutInflater.from(this).inflate(
									R.layout.wordwrap_edit, null);
							edittext.setLayoutParams(layoutParams);
							edittext.setPadding(DensityUtil.dip2px(this, 5), 0, DensityUtil.dip2px(this, 5), 0);
							edittext.setInputType(InputType.TYPE_NULL);
							edittext.setSingleLine(false);
							edittext.setTextSize(16);
							edittext.setTag(strsss);
							edittext.setTextColor(getResources().getColor(R.color.ask_right));
							if (Constants.ReadClassifyGroupType.TAB_SUMMARY.equals(data.group_type)
									|| Constants.ReadClassifyGroupType.TAB_SENTENCE_COMPLETION.equals(data.group_type)) {
								edittext.setText(StringUtil.deleteNo(myAnswer));
							} else {
								edittext.setText(myAnswer);
							}

							if (submitdata.questions.get(i).is_right.equals("false")) {
								edittext.setTextColor(getResources().getColor(R.color.ask_wrong));
							}
							edittext.setGravity(Gravity.CENTER);
							edittext.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, 0, 0);
							summary_tv_read_question.addView(edittext);
						} else {
							TextView textview = new TextView(this);
							textview.setLayoutParams(layoutParams);
							textview.setPadding(0, 0, 0, 0);
							textview.setTextSize(16);
							textview.setText(str);
							textview.setGravity(Gravity.CENTER);
							textview.setTextColor(Color.BLACK);
							summary_tv_read_question.addView(textview);
						}
					}
				}
			}

			mAnswerView.add(analysisview);
		}

	}

	private void initPointView() {
		for (int i = 0; i < data.questions_list.size(); i++) {
			ImageView imageView = new ImageView(this);
			imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			imageView.setImageResource(R.drawable.question_point_normal);
			imageView.setPadding(0, 0, 0, this.getResources().getDimensionPixelSize(R.dimen.read_16dp));
			mPointImageView.add(imageView);
			ll_read_click_question_point.addView(imageView);
		}
	}

	private void initOriginPager() {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		pagerFragment = new ReadOriginPagerFragment();
		Bundle bundle = new Bundle();
		bundle.putSerializable(Constants.READ_SETDATA_SINGLE_ORIGIN, origindata);
		bundle.putString(Constants.READ_ORIGIN_INDEX, data.category_id);
		pagerFragment.setArguments(bundle);
		transaction.replace(R.id.fragment_originpager, pagerFragment);
		transaction.commit();
	}

	@Override
	public void onClickEvent(View view) {
		switch (view.getId()) {
		case R.id.iv_topbar_back:
			finish();
			break;
		case R.id.tv_originpage:
			if (TextUtils.isEmpty(data.audio)) {
				// 友盟统计
				MobclickAgent.onEvent(this, "readExamAnswer_readText");
			} else {
				// 友盟统计
				MobclickAgent.onEvent(this, "listenExamAnswer_readText");
			}
			toggleOriginPager();
			break;
		case R.id.iv_read_exercises_pictrue:
			Intent intent = new Intent(this, PhotoViewActivity.class);
			intent.putExtra(Constants.READ_IMG_URL, data.img_1);
			startActivity(intent);
			break;

		case R.id.iv_read_exercises_pictrue2:
			Intent intent2 = new Intent(this, PhotoViewActivity.class);
			intent2.putExtra(Constants.READ_IMG_URL, data.img_2);
			startActivity(intent2);
			break;

		default:
			break;
		}
	}

	@Override
	public void onBackPressed() {
		if (fragment_originpager.getVisibility() == View.GONE) {
			finish();
		} else {
			toggleOriginPager();
		}
	}

	// 切出或隐藏原文
	private void toggleOriginPager() {
		if (fragment_originpager.getVisibility() == View.GONE) {
			AlphaAnimation alphaAnimation = new AlphaAnimation(0f, 1f);
			alphaAnimation.setDuration(duration * 2);
			fragment_originpager.startAnimation(alphaAnimation);
			alphaAnimation.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					tv_originpage.setBackgroundResource(R.drawable.original_pager_close);
					fragment_originpager.setVisibility(View.VISIBLE);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
				}
			});
		} else {
			AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0f);
			alphaAnimation.setDuration(duration * 2);
			fragment_originpager.startAnimation(alphaAnimation);
			alphaAnimation.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					tv_originpage.setBackgroundResource(R.drawable.original_pager);
					fragment_originpager.setVisibility(View.GONE);
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
				}
			});
		}

	}

	// 监听软键盘弹出，原文按钮出现与否，与练习的fragment绑定
	private void listenerSoftInput() {
		final View activityRootView = findViewById(R.id.fragment_practice);
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
				if (heightDiff > 300) {// 如果高度差超过300像素，就很有可能是有软键盘...
					tv_originpage.setVisibility(View.GONE);
				} else {
					tv_originpage.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_ANSWER);

		myLayoutTop = ll_read_top.getBottom();// 获取searchLayout的顶部位置
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_ANSWER);
	}

	@Override
	public void onScroll(int scrollY) {
		myLayoutTop = ll_read_top.getBottom();// 获取searchLayout的顶部位置
		if (scrollY >= myLayoutTop) {
			tv_fill_smalltitle.setVisibility(View.VISIBLE);
		} else {
			tv_fill_smalltitle.setVisibility(View.GONE);
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (null != mGestureDetector) {
			mGestureDetector.onTouchEvent(ev);
		}

		return super.dispatchTouchEvent(ev);
	}

	@Override
	public void isScrollBottom(boolean isBottom) {
		isScrollBottom = isBottom;
	}

	@Override
	public void isScrollTop(boolean isTop) {
		isScrollTop = isTop;
	}

}
